<template>
    <div class="content-container">
        <el-card>
            <!-- 查询部分 -->
            <el-form :model="query" :inline="true" class="demo-form-inline">
                <el-form-item label="角色名称">
                    <el-input v-model="query.name" clearable />
                </el-form-item>
                <el-form-item label="角色编码">
                    <el-input v-model="query.code" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="formQuery(false)">查询</el-button>
                    <el-button type="warning" @click="formQuery(true)">重置</el-button>
                    <el-button type="primary" @click="openDialog(null)">新增</el-button>

                    <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="确认删除选中数据?"
                        @confirm="removeRows" width="200px">
                        <template #reference>
                            <el-button type="danger">删除</el-button>
                        </template>
                    </el-popconfirm>
                </el-form-item>
            </el-form>
            <!-- 数据部分 -->
            <el-table max-height="600px" :data="tableData" stripe show-overflow-tooltip
                style="width: 100%; margin-top: 10px" ref="tableDataRef">
                <el-table-column type="selection" />
                <el-table-column prop="name" label="角色名称" />
                <el-table-column prop="code" label="角色编码" />
                <el-table-column prop="tenantOnly" label="角色性质">
                    <template #default="scope">
                        <el-tag style="cursor: pointer" :type="scope.row.tenantOnly == 1 ? 'danger' : 'success'">
                            {{ scope.row.tenantOnly == 1 ? '租户角色' : '普通角色' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" />
                <el-table-column prop="updateTime" label="修改时间" />
                <el-table-column fixed="right" label="操作">
                    <template #default="scope">
                        <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="确认转换角色性质?"
                            @confirm="switchRole(scope.row.id)" width="200px">
                            <template #reference>
                                <el-button link  type="primary">
                                    转换
                                </el-button>
                            </template>
                        </el-popconfirm>
                        <el-button @click="openDialog(scope.row)" link type="primary">
                            编辑
                        </el-button>
                        <el-button @click="m2rDialog(scope.row.id)" link type="primary">
                            授权
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 20px">
                <el-pagination v-model:current-page="query.current" v-model:page-size="query.size"
                    :page-sizes="[100, 200, 300, 400]" small background layout="total, sizes, prev, pager, next, jumper"
                    :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

            <el-dialog v-model="dialogVisible" :title="(formData.id ? '编辑' : '新增') + '角色信息'" width="40%"
                :show-close="false" :close-on-click-modal="false">
                <el-form :rules="rules" :model="formData" class="demo-form-inline" ref="formDataRef">
                    <el-form-item prop="name" label="角色名称">
                        <el-input v-model="formData.name" clearable />
                    </el-form-item>
                    <el-form-item prop="code" label="角色编码">
                        <el-input v-model="formData.code" clearable />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="formSubmit">确认</el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog v-model="m2rVisible" title="角色授权" width="40%" :show-close="false" :close-on-click-modal="false">
                <el-tree style="max-width: 600px" ref="treeRef" check-strictly :data="menus" show-checkbox node-key="id"
                    :props="{ label: 'title' }" default-expand-all />
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="m2rVisible = false">取消</el-button>
                        <el-button type="primary" @click="m2rConfirm">确认</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>
<script setup lang="ts" name="Role">
import { onMounted, reactive, ref, toRefs } from 'vue'
import type { Role, RoleModDTO, RoleQueryDTO } from '@/api/acl/role/type'
import {
    m2r,
    roleAdd,
    roleDel,
    roleMenus,
    roleMod,
    roleQuery,
    roleSwitch,
} from '@/api/acl/role'
import { ElNotification } from 'element-plus'
import { menuTree } from '@/api/acl/menu'
const treeRef = ref()
const formDataRef = ref()
const tableDataRef = ref()
const initQuery = () => {
    return { current: 1, size: 10 } as RoleQueryDTO
}
const state = reactive<any>({
    query: initQuery(),
    tableData: [] as Role[],
    total: 0,
    dialogVisible: false,
    m2rVisible: false,
    formData: {} as RoleModDTO,
    menus: [],
    dataScopes: [],
    roleId: '',
    rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        code: [{ required: true, message: '角色编码不能为空', trigger: 'blur' }],
        dataScope: [
            { required: true, message: '角色权限不能为空', trigger: 'blur' },
        ],
    },
})
const {
    query,
    tableData,
    total,
    dialogVisible,
    formData,
    rules,
    m2rVisible,
    menus,
    roleId
} = toRefs(state)

const openDialog = (data: any) => {
    if (formDataRef.value) {
        formDataRef.value.resetFields()
    }

    formData.value = data == null ? {} : data
    dialogVisible.value = true
}
const m2rConfirm = async () => {
    await m2r({
        roleId: roleId!.value,
        menuIds: treeRef.value!.getCheckedKeys(false),
    })
    m2rVisible.value = false
}
const m2rDialog = async (id: string) => {
    m2rVisible.value = true
    roleId.value = id
    const result = await roleMenus(id)
    treeRef.value!.setCheckedKeys(result.data, true)
}
const handleSizeChange = (size: number) => {
    query.value.size = size
    buildTable()
}
const handleCurrentChange = (current: number) => {
    query.value.current = current
    buildTable()
}
onMounted(() => {
    buildTable()
    buildMenus()
   // initScopes()
})
const buildTable = async () => {
    const result = await roleQuery(query.value)
    tableData.value = result.data.rows
    total.value = result.data.total
}
// const initScopes = async () => {
//     const result = await roleScopes()
//     dataScopes.value = result.data
// }

const buildMenus = async () => {
    const result = await menuTree()
    menus.value = result.data
}

const formQuery = (reset: boolean) => {
    reset ? (query.value = initQuery()) : query.value
    buildTable()
}
const formSubmit = async () => {
    await formDataRef.value?.validate()
    if (formData.value.id) {
        await roleMod(formData.value)
    } else {
        await roleAdd(formData.value)
    }
    dialogVisible.value = false
    await buildTable()
}
const removeRows = async () => {
    const rows = tableDataRef.value.getSelectionRows()
    if (rows.length == 0) {
        ElNotification({
            title: '删除失败',
            message: '请选择要删除的数据',
            type: 'warning',
        })
        return
    }
    const ids = rows.map((each: any) => each.id)
    await roleDel({ ids: ids })
    await buildTable()
}
const switchRole = async (id: string) => {
    await roleSwitch(id)
    await buildTable()
}
</script>


<style scoped lang="scss">
.content-container {
    padding: 12px;
}
</style>